package main

import (
	"fmt"
	"os"
	"os/signal"
	"syscall"
)

var server *EPoll

func main() {
	server = NewEpoll()
	e := server.Listen("0.0.0.0", 2010)
	if e != nil {
		fmt.Println(e)
		return
	}
	server.SetConnectEvent(connEvent)

	server.SetReceiveEvent(recEvent)

	go func() {
		for {
			e = server.HandlerEpoll()
			if e == syscall.EINTR {
				fmt.Println("handlerEpoll", e)
				//e = server.HandlerEpoll()
			}
		}
	}()
	go func() {
		if e = server.Accept(); e != nil {
			fmt.Println("accept:", e)
		}
	}()

	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Kill, os.Interrupt)
	<-c
	fmt.Println("==================END=======================")
	_ = server.Close()
	os.Exit(1)

}

func connEvent(b bool, cli *ServerConn) {
	if b {
		fmt.Printf("%s:%d 连接成功\n", cli.Addr, cli.Port)
	} else {
		fmt.Printf("%s:%d 断开连接\n", cli.Addr, cli.Port)
	}
	fmt.Println("连接数量:", server.GetConnectSum())
}

func recEvent(cli *ServerConn) {
	// fmt.Println("收到事件")
	var data = make([]byte, 4096)
	n, e := cli.Read(data)
	if n <= 0 || e != nil {
		fmt.Println("收据数据错，", e)
		return
	}
	fmt.Printf("接收到数据%d:%s\n", n, string(data[:n]))
	_, _ = cli.Write(data[:n])
	//_, _ = cli.Write(data[:n])
}
